package com.mch.func.file.html;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.apache.commons.io.FileUtils;
import org.mch.biz.handle.AbstractHandler;

/**
 * 描述：将HTML标签转换成小写处理器；<BR/>
 * 
 * @author MCH；<BR/>
 *
 */
public class ToHTMLLowerHandler extends AbstractHandler<String> {

	private File file;
	private String encode;
	private Set<String> ftset;

	private boolean isconver = false;

	public ToHTMLLowerHandler(File file, String encode, Set<String> ftset) {
		super();
		this.ftset = ftset;
		this.file = file;
		this.encode = encode;
	}

	@Override
	public String handle() throws Exception {
		if (this.file.isFile()) {
			return onConverFile();
		} else if (this.file.isDirectory()) {
			return onConverPath();
		}
		isconver = false;
		return "选择的文件或文件夹类型错误";
	}

	private String onConverFile() throws IOException {
		String str = FileUtils.readFileToString(this.file, this.encode);
		str = replaceHTML(str);
		isconver = true;
		return str;
	}

	/**
	 * 如果选择的是文件夹，则进行此处理；
	 * 
	 * @return
	 * @throws IOException
	 */
	private String onConverPath() throws IOException {

		// 获取文件夹下所有需要转换的文件；
		List<File> fileList = new ArrayList<File>();
		readFolderFiles(fileList, this.file);

		for (int i = 0, size = fileList.size(); i < size; i++) {
			File tmpfile = fileList.get(i);

			String str = FileUtils.readFileToString(tmpfile, this.encode);
			str = replaceHTML(str);

			String newStrFile = tmpfile.getPath().replace(this.file.getPath(), this.file.getPath() + "_low");
			File newfile = new File(newStrFile);

			FileUtils.writeStringToFile(newfile, str, this.encode);
			isconver = true;
		}

		if (isconver) {
			return "转换完成，转换文件已存到如下目录下 ：" + this.file.getPath() + "_low";
		} else {
			return "没有需要转换的文件";
		}
	}

	public String replaceHTML(String str) {
		String[] keys = HtmlMap.TAGMAP.keySet().toArray(new String[0]);
		for (int i = 0, len = keys.length; i < len; i++) {
			String key = keys[i];
			str = str.replace(key, HtmlMap.TAGMAP.get(key));
		}
		return str;
	}

	public void readFolderFiles(List<File> fileList, File file) {
		File[] files = file.listFiles();

		if (files != null && files.length > 0) {
			for (int i = 0, len = files.length; i < len; i++) {
				File tmpfile = files[i];
				if (tmpfile.isDirectory()) {
					readFolderFiles(fileList, tmpfile);
				} else {
					String path = tmpfile.getPath();
					String filetype = path.substring(path.lastIndexOf(".") + 1, path.length());
					if (this.ftset.contains(filetype.toLowerCase())) {
						fileList.add(tmpfile);
					}
				}
			}
		}
	}
}
